package cz.muni.fi.pa165.hauntedhouses.ejb;

import cz.muni.fi.pa165.hauntedhouses.entity.Ability;
import cz.muni.fi.pa165.hauntedhouses.util.Util;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.Local;
import javax.ejb.SessionContext;
import javax.ejb.Stateful;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * This class implement the AbilityDaoEJBLocal interface
 *
 * @author Jan Vyhnánek
 */
@Stateless
@Local(value=AbilityDaoEJBLocal.class)
public class AbilityDaoEJB implements AbilityDaoEJBLocal {
    
    @PersistenceContext(unitName = "TestPU")
    private EntityManager em;
    
    @Resource
    private SessionContext context;
    
    public void setEntityManager(EntityManager em){
        this.em = em;
    }
  
    @Override
    public void create(Ability ability) {
        Util.validateAbility(ability);
        if (ability.getId() != null) {
            throw new IllegalArgumentException("ID was already assigned");
        }
        em.persist(ability);
        em.flush();
        em.detach(ability);
    }

    @Override
    public void remove(Ability ability) {
        Util.validateAbility(ability);
        if (ability.getId() == null) {
            throw new IllegalArgumentException("This ability doesnt exist");
        }
        Ability abilityToRemove;
        abilityToRemove = em.find(Ability.class, ability.getId());
        em.remove(abilityToRemove);
    }

    @Override
    public Ability get(Long id) {
        if(id == null) {
            throw new IllegalArgumentException("ID is NULL");
        }
        if(id < 0) {
            throw new IllegalArgumentException("ID < 0");
        }
        Ability ability = em.find(Ability.class, id);
        em.detach(ability);
        return ability;
    }

    @Override
    public List<Ability> findAll() {
        Query q = em.createQuery("from Ability"); 
        List<Ability> abilities = q.getResultList();
        return Collections.unmodifiableList(abilities);
    }

   
}
